//api.js

const { log } = require('hexo/dist/plugins/helper/debug')
const connection = require('./db')
const { v4: uuidv4 } = require("uuid")
//  ⇨ 43d7e120-f963-11e8-999e-51f3e5aa256f
//查询
const getAccount = () => {
  return new Promise((resolve, reject) => {
    //第一个参数：sql语句
    //第二个参数：回调函数（err：查询错误，data：查询结果）
    connection.query("select * from account", (err, data) => {
      resolve(data)
    })
  })
}
//添加
const insertAccount = (param) => {
  return new Promise((resolve, reject) => {
    connection.query("insert into account(username,phone,password) values(?,?,?)", param, (err, data) => {
      //如果err为null则成功
      resolve(data)
    })
  })
}
//改
const updateAccount = (param) => {
  return new Promise((resolve, reject) => {
    connection.query("update account set username = ? where phone = ?", param, (err, data) => {
      //如果err为null则成功
      resolve(data)
    })
  })
}

//删除
const deleteAccount = (param) => {
  return new Promise((resolve, reject) => {
    connection.query("delete from account where id = ?", param, (err, data) => {
      resolve(data)
    })
  })
}

// 添加md笔记
const insertMd = (param) => {
  return new Promise((resolve, reject) => {
    const currentTime = new Date(); // 获取当前时间
    const sql = 'INSERT INTO article (title, content, type, id, create_time) VALUES (?,?,?,?,?)';
    const id = uuidv4();
    const values = [param.title, param.content, param.articleType, id, currentTime];
    connection.query(sql, values, (error, results) => {
      if (error) {
        reject(error);
      } else {
        resolve(results);
      }
    });
  });
}
// 定义函数用于查询article表所有数据并转为数组对象
const getAllArticles = () => {
  return new Promise((resolve, reject) => {
    const sql = 'SELECT * FROM article';
    connection.query(sql, (err, results) => {
      if (err) {
        reject(err);
      } else {
        // 将查询结果（数组形式，每条记录是一个对象）直接作为结果返回
        resolve(results);
      }
    });
  });
};

const getMd = () => {
  return new Promise((resolve, reject) => {
    connection.query("SELECT * FROM article", (err, data) => {
      //如果err为null则成功
      // console.log(data,123123123);
      resolve(data)
    })
  })
}

const getArticleById = (id) => {
  return new Promise((resolve, reject) => {
    const query = 'SELECT * FROM article WHERE id =?';

    connection.query(query, [id], (err, results) => {
      if (err) {
        reject(err);
      } else {
        console.log(results, 123123123);

        resolve(results[0]); // 一般返回的results是数组，第一条就是匹配的文章数据（如果有）
      }
    });
  });
}

// md上传图片
const uploadImg = () => {
  return new Promise((resolve, reject) => {

    connection.query("SELECT * FROM article", (err, data) => {
      //如果err为null则成功
      // console.log(data,123123123);
      resolve(data)
    })
  })
}

// 根据用户名查找用户
async function getUserByUsername(username) {
  console.log(username,123123123);
  
  const sql = 'SELECT * FROM users WHERE username = ?';
  // connection.query("SELECT * FROM article", (err, data) => {
  //   //如果err为null则成功
  //   // console.log(data,11111);
  //   resolve(data)
  // })
  // try {
  //   const results = await connection.query(sql, [username]);
  //   console.log('Query results:', results[0]);
  //   // MySQL2 返回的是 [rows, fields]，我们需要 rows
  //   // return results[0][0]; // 返回第一个匹配的用户
  // } catch (error) {
  //   console.error('Error getting user:', error);
  //   throw error;
  // }
  return new Promise((resolve, reject) => {

    connection.query("SELECT * FROM article", (err, data) => {
      //如果err为null则成功
      // console.log(data,123123123);
      resolve(data)
    })
  })
}

// 创建新用户
async function createUser({ username, password, email }) {
  const sql = 'INSERT INTO users (username, password, email) VALUES (?, ?, ?)';
  try {
    const results = await connection.query(sql, [username, password, email]);
    // MySQL2 返回的是 [rows, fields]
    const insertId = results[0].insertId;
    return {
      id: insertId,
      username,
      email
    };
  } catch (error) {
    console.error('Error creating user:', error);
    throw error;
  }
}

//导出方法，在需要使用到的模块中导入
module.exports = {
  getAccount,
  insertAccount,
  updateAccount,
  deleteAccount,
  insertMd,
  getMd,
  getAllArticles,
  getArticleById,
  getUserByUsername,
  createUser
}











